<template>
  <el-row class="details fff">
    <div class="step">
      <el-steps :active="active" finish-status="success">
        <el-step title="步骤 1" />
        <el-step title="步骤 2" />
      </el-steps>
    </div>
    <template v-if="!active">
      <el-row>
        <el-form
          ref="addForm"
          :inline="true"
          :rules="rules"
          :model="addForm"
          label-position="top"
          class="search"
        >
          <el-row>
            <el-col :span="6">
              <el-form-item label="货主编号" prop="code">
                <el-input v-model="addForm.code" disabled placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="货主名称" prop="name">
                <el-input
                  v-model="addForm.name"
                  placeholder="请输入"
                  :clearable="true"
                  max="10"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系人" prop="personName">
                <el-input
                  v-model="addForm.personName"
                  placeholder="请输入"
                  :clearable="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系人电话" prop="phone">
                <el-input
                  v-model="addForm.phone"
                  type="number"
                  placeholder="请输入"
                  :clearable="true"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="联系人邮箱">
                <el-input
                  v-model="addForm.email"
                  placeholder="请输入"
                  :clearable="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="省/市/区" prop="selectedOptions">
                <el-cascader
                  v-model="addForm.selectedOptions"
                  trigger="hover"
                  size="large"
                  :options="options"
                  :props="{ expandTrigger: 'hover' }"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="详细地址">
                <el-input
                  v-model="addForm.address"
                  placeholder="请输入"
                  :clearable="true"
                  max="10"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input
                v-model="addForm.remark"
                type="textarea"
                :rows="2"
                placeholder="请输入"
                :clearable="true"
                :max="50"
              />
            </el-form-item>
          </el-col>

        </el-form></el-row>

      <el-row class="submit">
        <el-button
          @click="$router.push('/manage-business/goods-owner')"
        >返回</el-button>
        <el-button type="primary" @click="onSubmit">下一步</el-button>
      </el-row>
    </template>
    <template v-else>
      <el-row class="allot">
        <el-col :span="3">
          <el-button
            type="success"
            @click="dialogVisible = true"
          >分配库位</el-button></el-col>
        <el-button
          @click="checked"
        >取消分配</el-button>
      </el-row>

      <div v-if="isNowData" class="now-data">
        <span class="imgIcon" /><span style="color: #b5abab;">暂无数据</span>
      </div>
      <template v-else>
        <el-table
          ref="table"
          :data="tableData.records"
          stripe
          border
          row-key="locationId"
          :row-style="{}"
          :header-cell-style="{
            background: '#f9f6ee',
            borderColor: '#f5efee!important',
            padding: '10px 0',
          }"
          :cell-style="{ borderColor: '#f5efee!important', padding: '10px 0' }"
        >
          <el-table-column
            type="selection"
            align="center"
          />
          <el-table-column label="序号" width="68" align="center">
            <template v-slot="{ $index }">{{ $index + 1 }}</template>
          </el-table-column>
          <el-table-column
            prop="warehouseName"
            label="仓库名称"
            align="center"
            width="150"
          />
          <el-table-column
            prop="areaName"
            label="库区名称"
            align="center"
            width="150"
          />
          <el-table-column
            prop="locationCode"
            label="库位编号"
            align="center"
            width="180"
          />
          <el-table-column
            prop="locationName"
            label="库位名称"
            align="center"
            width="200"
          />
          <el-table-column
            label="操作"
            align="center"
          >
            <template v-slot="{ row }">
              <span
                class="operate"
                @click="close(row)"
              >取消分配</span>
            </template>
          </el-table-column>
        </el-table>
        <PageTools
          :data="tableData"
          @handleSizeChange="handleSizeChangeFn"
          @handleCurrentChange="handleCurrentChangeFn"
        />
      </template>
      <el-row class="submit">
        <el-button
          @click="active--"
        >上一步</el-button>
        <el-button type="primary" @click="next">提交</el-button>
      </el-row>
    </template>
    <el-dialog
      title="分配货主库位"
      :visible.sync="dialogVisible"
      width="40%"
    >
      <el-form><el-form-item>
        <el-cascader
          v-model="locationList"
          :options="locationOptions"
          :props="{ multiple: true, }"
          clearable
        /></el-form-item></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="primary">确 定</el-button>
      </span>
    </el-dialog>

  </el-row>
</template>

<script>
import { regionData, CodeToText } from 'element-china-area-data'
import { nextCodeFactory } from '@/api/codeFactory'
import { addOwner, setOwner, queryOwner } from '@/api/owner'
import { queryAreaTree } from '@/api/area'
import { getOwnerLocationDetailsList, ownerLocationBatch, delOwnerLocation } from '@/api/ownerLocation'
import { getAllWarehouseList } from '@/api/wareHouse'
export default {
  data() {
    return {
      locationList: [],
      searchDate: { current: 1, size: 10, ownerId: '' },
      locationOptions: [],
      dialogVisible: false,
      active: 0,
      tableData: null,
      options: regionData,
      warehouseType: null,
      addForm: {
        code: null,
        name: null,
        personName: null,
        phone: null,
        email: null,
        selectedOptions: [],
        address: null,
        remark: null,
        location: null,
        province: null,
        city: null,
        area: null
      },
      rules: {
        name: {
          required: true,
          max: 10,
          message: '请输入货主名称',
          trigger: 'blur'
        },
        code: {
          required: true,
          message: '请输入',
          trigger: 'blur'
        },
        selectedOptions: {
          required: true,
          message: '请选择省/市/区',
          trigger: 'blur'
        },
        personName: {
          required: true,
          message: '请输入联系人',
          trigger: 'blur'
        },
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的电话号码' }
        ]
      }

    }
  },
  computed: {
    isNowData() {
      return !this.tableData?.records.length
    }
  },
  watch: {
    async active(val) {
      if (val) {
        this.getOwnerLocationDetailsList()
        this.getTree()
      }
    }
  },
  async created() {
    if (this.$route.params.id !== 'null') {
      const { data } = await queryOwner(this.$route.params.id)
      this.addForm = data
      this.addForm.selectedOptions = [data.province, data.city, data.area]
      console.log(this.addForm)
    } else {
      this.nextCodeFactory()
    }
  },
  methods: {
    async getOwnerLocationDetailsList() {
      const { data } = await getOwnerLocationDetailsList(this.searchDate)
      this.tableData = data
    },
    async getTree() {
      const { data } = await getAllWarehouseList({ status: 1 })
      this.locationOptions = data
      data.forEach(async(i, index) => {
        i.label = i.name
        i.value = i.id
        const res = await queryAreaTree({ '仓库id': i.id })
        res.data.forEach(i => { i.children.forEach(j => { j.disabled = !!j.ownerId }) })
        data[index].children = res.data
      })
    },
    async primary() {
      await ownerLocationBatch({ ownerId: this.searchDate.ownerId, idStrArray: this.locationList.map(i => i.join(',')) })
      this.$message.success('分配成功')
      this.getOwnerLocationDetailsList()
      this.dialogVisible = false
    },
    async nextCodeFactory() {
      const { data } = await nextCodeFactory('HZ')
      this.addForm.code = data
    },
    onSubmit() {
      this.addForm.location = this.addForm.selectedOptions.map((item, i) => CodeToText[this.addForm.selectedOptions[i]]).join('/')
      this.addForm.province = this.addForm.selectedOptions[0]
      this.addForm.city = this.addForm.selectedOptions[1]
      this.addForm.area = this.addForm.selectedOptions[2]
      this.$refs.addForm.validate(async(valid) => {
        if (valid) {
          // delete this.addForm.selectedOptions
          if (this.$route.params.id === 'null') {
            const { data } = await addOwner(this.addForm)
            this.searchDate.ownerId = data.id
            this.$message.success('新增成功')
          } else {
            const { data } = await setOwner(this.addForm)
            this.searchDate.ownerId = data.id
            this.$message.success('修改成功')
          }
          this.active++
        } else {
          this.$message.warning('请完善表单')
          return false
        }
      })
    },
    async checked() {
      if (!this.$refs.table?.selection?.length) {
        return this.$message.warning('请选择要取消数据')
      }
      this.$confirm(`确定要取消分配吗？`, '确认取消分配').then(
        async(_) => {
          await delOwnerLocation(this.$refs.table.selection.map(i => i.id))
          this.$message.success('取消成功')
          this.getOwnerLocationDetailsList()
        })
    },
    close(data) {
      this.$confirm(`确定要取消分配: ${data.locationName} 吗？`, '确认取消分配').then(
        async(_) => {
          await delOwnerLocation([data.id])
          this.getOwnerLocationDetailsList()
          this.$message.success('取消成功')
        }
      )
    },
    next() {
      this.$router.push('/manage-business/goods-owner')
    },
    handleSizeChangeFn(val) {
      this.searchForm.size = val
      this.searchForm.current = 1
      this.getWarehouseList()
    },
    handleCurrentChangeFn(val) {
      this.searchForm.current = val
      this.getWarehouseList()
    }
  }
}
</script>

<style lang="scss" scoped>
.submit {
  border-top: 1px solid #f5efee;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
  .el-button {
    width: 170px;
    margin: 20px;
  }
}
.step{
  width: 600px;
  height: 100px;
  margin: 56px auto 0;
}
.allot{
  padding: 20px;
}
 .el-form-item ::v-deep.el-form-item__content {
     height: auto;
}
.operate {
      color: #ffb200;
      cursor: pointer;
      &:hover {
        color: #ff8e00;
      }
      &.center {
        margin: 0 20px;
      }
    }
</style>
